#pragma once
#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>

using namespace SocketMoudle;
using namespace LogMoudle;
using ioservice_t=std::function<void(std::shared_ptr<Socket>& as,InetAddr& client)>;


class TcpServer
{
public:
    TcpServer(uint16_t port,ioservice_t service)
        : _port(port), _service(service), _isrunning(false),_listensockptr(std::make_unique<TcpSocket>())
    {
        _listensockptr->BuildTcpSocketMethod(_port);
    }
    void start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr as;
            auto sock =_listensockptr->Accept(&as);// 1. 和client通信sockfd 2. client 网络地址
            if(sock == nullptr)
            {
                continue;
            }
            LOG(loglevel::DEBUG) << "accept success ...";
            //  多进程
            pid_t id = fork();
            if (id < 0)
            {
                LOG(loglevel::FATAL) << "fork error";
                exit(FORK_ERR);
            }
            else if (id == 0)
            {
                _listensockptr->Close();
                if (fork() > 0) // 再次fork，子进程退出
                    exit(OK);

                _service(sock, as); // 孙子进程，孤儿进程，系统回收
                exit(OK);
            }
            else
            {
                sock->Close();
                pid_t rid = waitpid(id, nullptr, 0);
                (void)rid;
            } 
        }
        _isrunning = false;
    }
    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensockptr;
    ioservice_t _service;
    bool _isrunning;
};